//
//  WodeViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/18.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class WodeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SchoolSelectDelegate, FCLoginDelegate, UIImagePickerControllerDelegate , UINavigationControllerDelegate, TencentSessionDelegate {//QQApiInterfaceDelegate

    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    var tableView: UITableView!
    
    var editBtn: UIButton!
    var isUserEditing = false
    var userNameInput: UITextField!
    var sexSelector: UISegmentedControl!
    
    var userInfo: (name: String, sex: Int, area:String?, school: String?, avatar: String?)?
    var loginView: UIView!
    var loginInputView: FCLoginView!
    
    var schoolInfoLabel: UILabel!
    
    var loginBtn: UIButton!
    
    var bgID = 1
    
    var loadingView: LLFullScreenLoading!
    
    var avaImgBtn: UIButton!
    
    var bgImgView: UIImageView!
    
    var cachesSize = 0.0
    
    var cachesSizeLabel: UILabel!
    
    var tencentApi: TencentOAuth?
    
    override func viewDidLoad() {
        
        let appDelegate = UIApplication.shared.delegate as? AppDelegate
        appDelegate?.wodeVCLoaded = true
        
        navigationController?.setNavigationBarHidden(true, animated: false)
        view.backgroundColor = UIColor.groupTableViewBackground
        
        
        super.viewDidLoad()
        tableView = UITableView(frame: CGRect(x: 0, y: -20, width: view.bounds.width, height: view.bounds.height - 64))
        tableView.backgroundColor = UIColor.groupTableViewBackground
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isScrollEnabled = false
        view.addSubview(tableView)
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        
        bgImgView = UIImageView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 150))
        bgImgView.backgroundColor = UIColor.lightGray
        bgImgView.image = UIImage(named: "wode\(bgID)")
        
        editBtn = UIButton(frame: CGRect(x: view.bounds.width - 72, y: 28, width: 64, height: 20))
        editBtn.setTitle("修", for: .normal)
        editBtn.setImage(#imageLiteral(resourceName: "edit"), for: .normal)
        editBtn.imageView?.contentMode = .scaleAspectFit
        editBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        
        editBtn.addTarget(self, action: #selector(WodeViewController.toggleUserEdit), for: .touchUpInside)
        
        avaImgBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        avaImgBtn.center = CGPoint(x: view.center.x, y: 150)
        avaImgBtn.backgroundColor = UIColor.lightGray
        avaImgBtn.layer.cornerRadius = 50
        avaImgBtn.layer.borderWidth = 2
        avaImgBtn.layer.borderColor = UIColor.white.cgColor
        avaImgBtn.layer.masksToBounds = true
        avaImgBtn.addTarget(self, action: #selector(WodeViewController.changeAvatar), for: .touchUpInside)
        
        userNameInput = UITextField(frame: CGRect(x: 64, y: 8, width: view.bounds.width - 64 - 16, height: 28))
        userNameInput.textColor = themeColor1
        userNameInput.font = UIFont.systemFont(ofSize: 14)
        userNameInput.placeholder = "请输入昵称"
        userNameInput.returnKeyType = .done
        userNameInput.enablesReturnKeyAutomatically = true
        userNameInput.addTarget(self, action: #selector(WodeViewController.textInputEnd(sender:)), for: .editingDidEndOnExit)
        
        sexSelector = UISegmentedControl(items: ["男", "女", "保密"])
        sexSelector.frame = CGRect(x: 64, y: 8, width: (view.bounds.width - 80)/2, height: 28)
        sexSelector.tintColor = themeColor1
        
        loginView = UIView(frame: view.frame)
        loginView.backgroundColor = themeColor2
        
        let bgView = UIImageView(frame: loginView.frame)
        
        bgView.image = #imageLiteral(resourceName: "loginBG")
        loginView.addSubview(bgView)
        
        loginBtn = UIButton(frame: CGRect(x: 0, y: view.bounds.height - 156, width: 120, height: 44))
        loginBtn.center.x = view.center.x
        loginBtn.backgroundColor = UIColor(white: 1, alpha: 0.6)
        loginBtn.setTitle("登陆", for: .normal)
        loginBtn.setTitleColor(themeColor2, for: .normal)
        loginBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        loginBtn.layer.borderColor = UIColor.white.cgColor
        loginBtn.layer.borderWidth = 1
        loginBtn.layer.cornerRadius = 8
        loginView.addSubview(loginBtn)
        loginBtn.addTarget(self, action: #selector(WodeViewController.showLoginDialog), for: .touchUpInside)
        
        loginView.alpha = 0
        
        view.addSubview(loginView)
        
        loginInputView = FCLoginView(frame: view.frame)
        loginInputView.delegate = self
        loginInputView.alpha = 0
        view.addSubview(loginInputView)
        loginInputView.closeBtn.addTarget(self, action: #selector(WodeViewController.hideLoginDialog), for: .touchUpInside)
        loginInputView.regBtn.addTarget(self, action: #selector(WodeViewController.gotoRegView), for: .touchUpInside)
        loginInputView.forgetBtn.addTarget(self, action: #selector(WodeViewController.gotoForgetPassword), for: .touchUpInside)
        loginInputView.qqLoginBtn.addTarget(self, action: #selector(WodeViewController.goQQLogin), for: .touchUpInside)
        
        schoolInfoLabel = UILabel(frame: CGRect(x: 96, y: 8, width: view.bounds.width - 96 - 16, height: 28))
        schoolInfoLabel.textColor = themeColor1
        schoolInfoLabel.font = UIFont.systemFont(ofSize: 14)
        
        cachesSizeLabel = UILabel(frame: CGRect(x: view.bounds.width/2, y: 8, width: view.bounds.width/2 - 16, height: 28))
        cachesSizeLabel.font = UIFont.systemFont(ofSize: 14)
        cachesSizeLabel.textAlignment = .right
        cachesSizeLabel.textColor = UIColor.lightGray
        cachesSizeLabel.text = "0.0M"
        
        loadingView = LLFullScreenLoading(frame: view.frame)
        view.addSubview(loadingView)
        loadingView.alpha = 0
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        loadUserData()
        
        //MARK: 获取缓存大小
        DispatchQueue(label: "filesize").async {
            print("caches")
            let ls = try? FileManager.default.contentsOfDirectory(atPath: "\(DOCUMENT_PATH)/Inbox")
            if ls != nil {
                print(ls!)
                var totalSize = 0.0
                for item in ls!{
                    let info = try? FileManager.default.attributesOfItem(atPath: "\(DOCUMENT_PATH)/Inbox/\(item)")
                    if info != nil{
                        let size = (info![FileAttributeKey.size] as? NSNumber)?.doubleValue
                        if size != nil{
                            totalSize += size!
                        }
                    }
                }
                print(totalSize)
                totalSize /= 1024*1024
                var mb = "M"
                if totalSize > 1024 {
                    totalSize /= 1024
                    mb = "G"
                }
                
                DispatchQueue.main.async {
                    self.cachesSize = totalSize
                    self.cachesSizeLabel.text = String(format: "%.1lf\(mb)", totalSize)//self.cachesSize
                }
            }
        }
    }
    
    func loadUserData(){
        let userData = getUserInfo() as? [String: Any?]
        
        if !isLogin() {
            tableView.alpha = 0
            loginView.alpha = 1
            return
        }else{
//            if loginInputView.alpha == 1{
//                
//            }
            hideLoginDialog()
            tableView.alpha = 1
            loginView.alpha = 0
        }
        
        userInfo = ("用户", 0, nil, nil, nil)
        
        let userName = userData?[userNickNameDefaultKeyName] as? String
        userInfo?.name = userName ?? "用户"
        
        
        let userArea = userData?[userAreaDefaultKeyName] as? String
        userInfo?.area = userArea
        
        let userSchool = userData?[userSchoolDefaultKeyName] as? String
        userInfo?.school = userSchool
        
        
        let bgDefault = UserDefaults.standard.object(forKey: wodeImageKeyName)
        if bgDefault != nil{
            let bgInt = bgDefault as? Int
            if bgInt != nil {
                bgID = bgInt!
            }
        }
        
        let userSex = userData?[userSexDefaultKeyName] as? Int
        userInfo?.sex = userSex ?? 0
        
//        loadingView.alpha = 1
        
        URLSession.shared.dataTask(with: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo")!) { (data:Data?, resp:URLResponse?, err:Error?) in
            DispatchQueue.main.async {
                self.loadingView.alpha = 0
            }
            do{
                if err != nil{
                    throw err!
                }
                
                print(String(data: data!, encoding: .utf8) ?? "data nil")
                
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                
                let nickName = jsonData?.object(forKey: "nickname") as? String
                if nickName != nil{
                    self.userInfo?.name = nickName!
                }
                let sex = jsonData?.object(forKey: "sex") as? String
                if sex != nil{
                    self.userInfo?.sex = self.getSexID(withName: sex!)
                }
                let school = jsonData?.object(forKey: "school") as? String
                self.userInfo?.school = school
                let face = jsonData?.object(forKey: "face") as? String
                self.userInfo?.avatar = face
                
                if face != nil{
                    let avatarUrl = URL(string: face!)//"\(baseDomainName)/\(face!)")
                    if avatarUrl != nil{
                        URLSession.shared.dataTask(with: avatarUrl!, completionHandler: { (data:Data?, re:URLResponse?, err:Error?) in
                            if err == nil{
                                if data != nil{
                                    DispatchQueue.main.async {
                                        self.avaImgBtn.setImage(UIImage(data: data!), for: .normal)
                                    }
                                }
                            }
                        }).resume()
                    }
                }
                
                
            }catch let ex{
                print(ex)
                let alert = UIAlertController(title: "获取失败", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                DispatchQueue.main.async {
                    self.present(alert, animated: true, completion: nil)
                }
            }
            DispatchQueue.main.async {
                
                self.tableView.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .none)
                self.userNameInput.text = self.userInfo?.name ?? "用户"
                if self.userInfo!.sex >= 0 && self.userInfo!.sex <= 2{
                    self.sexSelector.selectedSegmentIndex = (self.userInfo!.sex + 2) % 3
                }
                self.schoolInfoLabel.text = self.userInfo?.school
            }
        }.resume()
        
    }
    
    func getSexID(withName: String) ->Int {
        switch withName {
        case "男":
            return 1
        case "女":
            return 2
        default:
            return 0
        }
    }
    
    func getSexName(withID: Int) -> String {
        switch withID {
        case 1:
            return "男"
        case 2:
            return "女"
        default:
            return "保密"
        }
    }
    
    //MARK: maybe 动画?
    func showLoginDialog(){
        loginInputView.alpha = 1
        loginBtn.alpha = 0
    }
    
    func hideLoginDialog(){
        loginInputView.userNameInput.input.resignFirstResponder()
        loginInputView.passwordInput.input.resignFirstResponder()
        loginInputView.alpha = 0
        loginBtn.alpha = 1
    }
    
    func changeBGImage(){
        bgID = (bgID) % 4 + 1
        UserDefaults.standard.setValue(bgID, forKey: wodeImageKeyName)
//        tableView.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .fade)
        UIView.animate(withDuration: 0.3) { 
            self.bgImgView.image = UIImage(named: "wode\(self.bgID)")
        }
       
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1{
            return isUserEditing ? 3 : 0
        }
        if section == 2{
            return 3//4
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 && indexPath.row == 0{
            return 300
        }
        return 44
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        cell.selectionStyle = .none
        switch indexPath.section{
        case 0:
            
            if indexPath.row == 0{
                
                cell.addSubview(bgImgView)
                
                let changeBtn = UIButton(frame: CGRect(x: 8, y: 28, width: 48, height: 20))
                changeBtn.setTitle("换", for: .normal)
                changeBtn.setImage(#imageLiteral(resourceName: "change"), for: .normal)
                changeBtn.imageView?.contentMode = .scaleAspectFit
                changeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                cell.addSubview(changeBtn)
                changeBtn.addTarget(self, action: #selector(WodeViewController.changeBGImage), for: .touchUpInside)
                
                cell.addSubview(editBtn)
                
                cell.addSubview(avaImgBtn)
//                let imgURLStr = userInfo?.avatar
//                if imgURLStr != nil{
//                    let imgURL = URL(string: imgURLStr!)
//                    if imgURL != nil{
//                        URLSession.shared.dataTask(with: imgURL!, completionHandler: { (data:Data?, re:URLResponse?, err:Error?) in
//                            if err == nil{
//                                if data != nil{
//                                    DispatchQueue.main.async {
//                                        self.avaImgBtn.setImage(UIImage(data: data!), for: .normal)
//                                    }
//                                }
//                            }
//                        }).resume()
//                    }
//                }
                
                
                let nameLabel = UILabel(frame: CGRect(x: 16, y: 216, width: view.bounds.width - 32, height: 36))
                nameLabel.font = UIFont.systemFont(ofSize: 24)
                nameLabel.textAlignment = .center
                cell.addSubview(nameLabel)
                
                let infoLabel = UILabel(frame: CGRect(x: 16, y: 256, width: view.bounds.width - 32, height: 20))
                infoLabel.font = UIFont.systemFont(ofSize: 14)
                infoLabel.textAlignment = .center
                cell.addSubview(infoLabel)
                
                
                nameLabel.text = userInfo?.name ?? "用户"
                
                var showedItemCount = 0
                
                var showStr = ""
                let userSex = userInfo?.sex
                if userSex != nil{
                    if userSex != 0 {
                        showStr += userSex! == 1 ? "男" : "女"
                        showedItemCount += 1
                    }
                }
                
                
                let userArea = userInfo?.area
                if userArea != nil{
                    if showedItemCount != 0{
                        showStr += " / "
                    }
                    showStr += userArea!
                    showedItemCount += 1
                }
                
                let userSchool = userInfo?.school
                if userSchool != nil{
                    if userSchool != "" {
                        if showedItemCount != 0{
                            showStr += " / "
                        }
                        showStr += userSchool!
                        showedItemCount += 1
                    }
                    
                }
                
                infoLabel.text = showStr
            }
            break
        case 1:
            cell.textLabel?.font = UIFont.systemFont(ofSize: 16)
            cell.textLabel?.textColor = themeColor2
            switch indexPath.row {
                
            case 0:
                cell.textLabel?.text = "昵称"
                cell.addSubview(userNameInput)
                break
            case 1:
                cell.textLabel?.text = "性别"
                cell.addSubview(sexSelector)
                break
            case 2:
                cell.selectionStyle = .default
                cell.textLabel?.text = "所在院校"
                
                cell.addSubview(schoolInfoLabel)
                
                break
            default:
                break
            }
            break
        case 2:
            let iconIV = UIImageView(frame: CGRect(x: 16, y: 16, width: 16, height: 16))
            //            iconIV.backgroundColor = UIColor.lightGray
            //            iconIV.contentMode = .center
            cell.addSubview(iconIV)
            
            let titleLabel = UILabel(frame: CGRect(x: 40, y: 8, width: view.bounds.width/2 - 34, height: 28))
            titleLabel.font = UIFont.systemFont(ofSize: 16)
            titleLabel.textColor = littleGrayColor
            cell.addSubview(titleLabel)
            
            let subLabel = UILabel(frame: CGRect(x: view.bounds.width/2, y: 8, width: view.bounds.width/2 - 16, height: 28))
            subLabel.font = UIFont.systemFont(ofSize: 14)
            subLabel.textAlignment = .right
            subLabel.textColor = UIColor.lightGray
            cell.addSubview(subLabel)
            
            switch indexPath.row {
//            case 0:
//                iconIV.image = #imageLiteral(resourceName: "favorite")
//                titleLabel.text = "收藏"
//                break
            case 0://1:
                cell.selectionStyle = .default
                iconIV.image = #imageLiteral(resourceName: "trash")
                titleLabel.text = "清理缓存"
//                subLabel.text = "0.0M"
                
                
                cell.addSubview(cachesSizeLabel)
                
                break
            case 1://2:
                cell.selectionStyle = .default
                iconIV.image = #imageLiteral(resourceName: "update")
                titleLabel.text = "版本"
                subLabel.text = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
                
                break
            case 2:
                cell.selectionStyle = .default
                iconIV.image = #imageLiteral(resourceName: "exit")
                titleLabel.text = "退出登录"
                
                break
            default:
                break
            }
            break
        default:
            break
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 1 && indexPath.row == 2{
            print("修改学校")
            //MARK:修改学校
            hidesBottomBarWhenPushed = true
            let schoolVC = SchoolViewController()
            schoolVC.delegate = self
            navigationController?.pushViewController(schoolVC, animated: true)
        }
        if indexPath.section == 2 && indexPath.row == 0{
            print("clear caches")
            // MARK: 清理缓存
            DispatchQueue(label: "clearCaches").async {
                let ls = try? FileManager.default.contentsOfDirectory(atPath: "\(DOCUMENT_PATH)/Inbox")
                if ls != nil {
                    print(ls!)
                    DispatchQueue.main.async {
                        self.cachesSizeLabel.text = "清理中"
                    }
                    for item in ls!{
                        _ = try? FileManager.default.removeItem(atPath: "\(DOCUMENT_PATH)/Inbox/\(item)")
                    }
                    DispatchQueue.main.async {
                        self.cachesSizeLabel.text = "0.0M"
                    }
                }
                
            }
        }
        if indexPath.section == 2 && indexPath.row == 2{
            print("退出")
            // MARK: 退出登录
            let alert = UIAlertController(title: "退出登录?", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "退出", style: .default, handler: { (action) in
                UserDefaults.standard.removeObject(forKey: loginUserDefaultKeyName)
                self.loadUserData()
                ChangyanSDK.logout()
                
                var remoteLogout = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=login&a=userLogout")!)
                remoteLogout.httpMethod = "POST"
//                remoteLogout.httpBody = "".data(using: .utf8)
                URLSession.shared.dataTask(with: remoteLogout, completionHandler: { (data, _, err) in
                    do{
                        if err != nil{
                            throw err!
                        }
                        
                        print(String(data: data!, encoding: .utf8) ?? "data nil")
                        
//                        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                        
                        
                    }catch let ex{
                        print(ex)
                    }
                }).resume()
            }))
            alert.addAction(UIAlertAction(title: "不退出", style: .cancel, handler: nil))
            present(alert, animated: true, completion: nil)
            
        }
    }
    
    func changeAvatar(){
        
        
        let options = UIAlertController(title: "修改头像", message: nil, preferredStyle: .actionSheet)
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.allowsEditing = true
        options.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (action) in
            
            if UIImagePickerController.isCameraDeviceAvailable(.rear) || UIImagePickerController.isCameraDeviceAvailable(.front) {
                picker.sourceType = .camera
                self.present(picker, animated: true, completion: nil)
            }else{
                let alert = UIAlertController(title: "无法打开相机", message: "设置-隐私-相机-喵印-打开", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
            
        }))
        options.addAction(UIAlertAction(title: "选择照片", style: .default, handler: { (action) in
            picker.sourceType = .photoLibrary
            self.present(picker, animated: true, completion: nil)
        }))
        options.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        present(options, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        DispatchQueue.main.async {
            picker.dismiss(animated: true, completion: nil)
        }
        let image = info[UIImagePickerControllerEditedImage] as? UIImage
        if image != nil{
            
            let smallSize = CGSize(width: 200, height: 200)
            
            UIGraphicsBeginImageContext(smallSize)
            image!.draw(in: CGRect(origin: CGPoint.zero, size: smallSize))
            let smallImage = UIGraphicsGetImageFromCurrentImageContext()
            
            DispatchQueue.main.async {
                self.avaImgBtn.setImage(smallImage, for: .normal)
            }
            
            if smallImage != nil{
                let imageData = UIImageJPEGRepresentation(smallImage!, 0.5)
                
                var postData = Data()
                
                postData.append("--AaB03x\r\nContent-Disposition: form-data; name=\"face\"; filename=\"filename.jpg\"\r\nContent-Type: image/jpg\r\n\r\n".data(using: .utf8)!)
                postData.append(imageData!)
                postData.append("\r\n--AaB03x--\r\n".data(using: .utf8)!)
                
                var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=index&a=editInfo")!)
                resq.httpMethod = "POST"
                resq.setValue("multipart/form-data; boundary=AaB03x", forHTTPHeaderField: "Content-Type")
                resq.setValue("\(postData.count)", forHTTPHeaderField: "Content-Length")
                print(resq.allHTTPHeaderFields ?? "nil")
                resq.httpBody = postData
                
                URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, re:URLResponse?, er:Error?) in
                    do{
                        print(String(data: data!, encoding: .utf8) ?? "data nil")
                        
                        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                        let code = jsonObj?.object(forKey: "code") as? Int
                        if code != 200 {
                            let msg = jsonObj?.object(forKey: "message") as? String
                            let alert = UIAlertController(title: msg, message: nil, preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                            DispatchQueue.main.async {
                                self.present(alert, animated: true, completion: nil)
                            }
                        }
                    }catch let ex{
                        let alert = UIAlertController(title: "修改失败", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                        print(ex)
                    }
                }).resume()
            }
            
            
        }
    }
    
    func schoolView(data: Any) {
        let info = data as? NSDictionary
        let schoolInfo = info?.object(forKey: "school") as? NSDictionary
        let name = schoolInfo?.object(forKey: "name") as? String
        let majorInfo = info?.object(forKey: "major") as? NSDictionary
        let majorName = majorInfo?.object(forKey: "name") as? String
        var showName = ""
        if name != nil{
            showName += name!
        }
        if majorName != nil {
            showName += majorName!
        }
        schoolInfoLabel.text = showName
        
        
        let sID = schoolInfo?.object(forKey: "id") as? String
        let mID = majorInfo?.object(forKey: "id") as? String
        if sID != nil || mID != nil{
            var postData = ""
            if sID != nil{
                postData += "univsId=\(sID!)"
            }
            if mID != nil{
                postData += "&schoolId=\(mID!)"
            }
            print(postData)
            var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=index&a=editInfo")!)
            resq.httpMethod = "POST"
            resq.httpBody = postData.data(using: .utf8)
            
            URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, re:URLResponse?, er:Error?) in
                do{
                    print(String(data: data!, encoding: .utf8) ?? "data nil")
                    
                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    let code = jsonObj?.object(forKey: "code") as? Int
                    if code != 200 {
                        let msg = jsonObj?.object(forKey: "message") as? String
                        let alert = UIAlertController(title: msg, message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                    }
                }catch let ex{
                    let alert = UIAlertController(title: "修改失败", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                    print(ex)
                }
            }).resume()
        }
    }
    
    
    func toggleUserEdit(){
        isUserEditing = !isUserEditing
        editBtn.setTitle(isUserEditing ? "完成" : "修", for: .normal)
        tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .automatic)
        if !isUserEditing{
            
            var newName: String?
            var newSex: String?
            
            if userNameInput.text != "" {
                if userInfo?.name != userNameInput.text{
                    newName = userNameInput.text
                }
                
                userInfo?.name = userNameInput.text!
                
                
            }
            
            if sexSelector.selectedSegmentIndex >= 0 && sexSelector.selectedSegmentIndex <= 2{
                let selSex = (sexSelector.selectedSegmentIndex + 1) % 3
                if userInfo?.sex != selSex {
                    newSex = getSexName(withID: selSex)
                }
                userInfo?.sex = (sexSelector.selectedSegmentIndex + 1) % 3
                
            }
            
//            userInfo?.school = schoolInfoLabel.text
            
            tableView.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .none)
            
            
            
            if newName != nil || newSex != nil{
                var compo =  ""
                if newName != nil{
                    compo += "nickname=\(newName!)"
                }
                if newSex != nil {
                    compo += "&sex=\(newSex!)"
                }
                var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=index&a=editInfo")!)
                resq.httpMethod = "POST"
                resq.httpBody = compo.data(using: .utf8)
                
                URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, re:URLResponse?, er:Error?) in
                    do{
                        print(String(data: data!, encoding: .utf8) ?? "data nil")
                        
                        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                        let code = jsonObj?.object(forKey: "code") as? Int
                        if code != 200 {
                            let msg = jsonObj?.object(forKey: "message") as? String
                            let alert = UIAlertController(title: msg, message: nil, preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                            DispatchQueue.main.async {
                                self.present(alert, animated: true, completion: nil)
                            }
                        }
                    }catch let ex{
                        let alert = UIAlertController(title: "修改失败", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                        print(ex)
                    }
                }).resume()
            }
            
        }
    }
    
    func textInputEnd(sender: UITextField){
        sender.resignFirstResponder()
    }
    
    func gotoRegView(){
        let nav = UINavigationController(rootViewController: UDRegViewController())
        nav.setNavigationBarHidden(true, animated: false)
        nav.modalTransitionStyle = .crossDissolve
        present(nav, animated: true, completion: nil)
    }
    
    func gotoForgetPassword(){
        let nav = UINavigationController(rootViewController: UDRegViewController(action: .forgetPassword))
        nav.setNavigationBarHidden(true, animated: false)
        nav.modalTransitionStyle = .crossDissolve
        present(nav, animated: true, completion: nil)
    }
    
    func loginView(_ loginView: FCLoginView, successLogin data: Any?) {
        
        loadUserData()
    }
    
    func loginView(_ loginView: FCLoginView, loginFailed data: Any?) {
        
        var errMsg = "请求出错"
        
        if data != nil{
            let jsonObj = data as? NSDictionary
            if jsonObj != nil{
                
                errMsg = jsonObj?.object(forKey: "message") as? String ?? "请求出错"
            }
        }
        let alert = UIAlertController(title: errMsg, message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        hidesBottomBarWhenPushed = false
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func gotoBindVC(type: BindAccountType, code: String?, openid: String?){
        
        let bindVC = UINavigationController(rootViewController: BindViewController(bindType: type, code: code, openid: openid))
        bindVC.setNavigationBarHidden(true, animated: false)
        present(bindVC, animated: true, completion: nil)
    }

    func goQQLogin(){
        if tencentApi == nil{
            tencentApi = TencentOAuth(appId: "101382009", andDelegate: self)
        }
        let permission:[Any] = [
            kOPEN_PERMISSION_GET_USER_INFO,
            kOPEN_PERMISSION_GET_SIMPLE_USER_INFO
        ]
//        NSArray(objects: "get_user_info",) as [Any]
        tencentApi?.authorize(permission, inSafari: false)
//        tencentApi?.authorize(permission)
        
//        let mahuateng = (UIApplication.shared.delegate as? AppDelegate)?.tencentApi
//        mahuateng?.goLogin()
        
//        sdkCall.getinstance().oauth.authorize(permission)
        
    }
    
    public func tencentDidLogin() {
//        print("tencentDidLogin: \(tencentApi?.accessToken ?? "openid nil")")
        
//        var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=login&a=qqGetOpenId")!)
//        resq.httpMethod = "POST"
//        resq.httpBody = "access_token=\(tencentApi?.accessToken ?? "")".data(using: .utf8)
        
        let openID = tencentApi?.openId
        
        print("miaoyin_union_openid: \(openID ?? "data nil")")
        
        
        
        if openID != nil {
            var loginReq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=login&a=appQQLogin")!)
            loginReq.httpMethod = "POST"
            loginReq.httpBody = "openid=\(openID!)".data(using: .utf8)
            URLSession.shared.dataTask(with: loginReq, completionHandler: { (dataa, _, errr) in
                do{
                    if errr != nil{
                        throw errr!
                    }
                    
                    print(String(data: dataa!, encoding: .utf8) ?? "dataa nil")
                    
                    let jsonObj = try JSONSerialization.jsonObject(with: dataa!, options: .allowFragments) as? NSDictionary
                    let reCode = jsonObj?.object(forKey: "code") as? Int
                    
                    if reCode == 200{
                        
                        let cookies = HTTPCookieStorage.shared.cookies!
                        let cookiesData = NSKeyedArchiver.archivedData(withRootObject: cookies)
                        UserDefaults.standard.set(cookiesData, forKey: cookieKey)
                        UserDefaults.standard.set(openID!, forKey: loginUserDefaultKeyName)
                        
                        DispatchQueue.main.async {
                            
                            self.loadUserData()
                        }
                        
                        URLSession.shared.dataTask(with: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo")!) { (data:Data?, resp:URLResponse?, err:Error?) in
                            do{
                                if err != nil{
                                    throw err!
                                }
                                
                                print(String(data: data!, encoding: .utf8) ?? "data nil")
                                
                                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                                let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                                
                                let nickName = jsonData?.object(forKey: "nickname") as? String
                                let face = jsonData?.object(forKey: "face") as? String
                                
                                if !ChangyanSDK.isLogin(){
                                    ChangyanSDK.loginSSO(openID!, userName: nickName ?? "", profileUrl: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo", imgUrl: face ?? "", complete: { (code, msg) in
                                        if code == CYSuccess {
                                            print("changyan login success:")
                                            print(msg ?? "no respond")
                                        }
                                    })
                                }
                                
                            }catch let ex{
                                print(ex)
                            }
                            }.resume()
                        
                        
                    }else if reCode == 201 {
                        DispatchQueue.main.async {
//                                    self.tabController.selectedIndex = 2
//                                    self.tabController.presentedViewController?.dismiss(animated: true, completion: nil)
//                                    self.tabController.bgView.alpha = 0
//                                    self.tabController.fileView?.alpha = 0
                            self.gotoBindVC(type: .qq, code: nil, openid: openID)
                        }
                    }else{
                        let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                    }
                    
                    
                }catch let exx{
                    let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                    print(exx)
                }
            }).resume()
        }
        
        
//        URLSession.shared.dataTask(with: resq) { (data, _, err) in
//            do{
//                if err != nil{
//                    throw err!
//                }
//                
//                let unionID = String(data: data!, encoding: .utf8)
//                
//                
//            }catch let ex{
//                let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
//                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
//                DispatchQueue.main.async {
//                    self.present(alert, animated: true, completion: nil)
//                }
//                print(ex)
//            }
//        }.resume()
    }
    
    
    public func tencentDidNotLogin(_ cancelled: Bool) {
        
    }
    
    
    func tencentDidNotNetWork() {
        
    }
    
//    func onReq(_ req: QQBaseReq!) {
//        
//    }
//    func onResp(_ resp: QQBaseResp!) {
//        
//    }
    
    func isOnlineResponse(_ response: [AnyHashable : Any]!) {
        
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
